<?php

namespace App\Library\Guanyuan;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class GuanyuanTool
{
    /**
     * 获取观远数据原始记录表
     * @param string $source 例如：s580b6c8918224fdfa8da24b，https://kuafu.guandatacloud.com/data-source/s580b6c8918224fdfa8da24b/details/overview
     * @param string $token 例如：i99f447954eda4fbxxxxxxxx，夏目同学可以生成token
     * @param array $filters https://thoughts.teambition.com/sharespace/616fb6829cdb8400410e91ac/docs/6328547cfdd87e0041cd3fb4
     * @return array
     * @throws GuzzleException
     */
    public static function fetch(string $source, string $token, array $filters = []): array
    {
        $url      = "https://kuafu.guandatacloud.com/public-api/data-source/{$source}/token/{$token}";
        $response = (new Client(['http_errors' => false]))->post($url, ['json' => ['filters' => $filters]]);
        $body     = $response->getBody()->getContents();
        $arr      = json_decode($body, true);
        return static::formatList($arr);
    }

    /**
     * 格式化观远数据
     * @param array $arr
     * @return array
     */
    public static function formatList(array $arr): array
    {
        $columns       = $arr['response']['columns'] ?? [];
        $list          = $arr['response']['data'] ?? [];
        $formattedList = [];
        foreach ($list as $item) {
            $newItem = [];
            foreach ($item as $k => $v) {
                $newK           = $columns[$k];
                $newItem[$newK] = $v;
            }
            $formattedList[] = $newItem;
        }
        return $formattedList;
    }
}
